package info.motteke.kurumi.swt;

import info.motteke.kurumi.SimpleStringVisitor;
import info.motteke.kurumi.VoiceBlock;
import info.motteke.kurumi.VoiceSelectedListener;
import info.motteke.mixivoice4j.Voice;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;

public class SwtHistoryBlock implements VoiceBlock {

    private static final Log log = LogFactory.getLog(SwtHistoryBlock.class);

    private final Composite c;

    private final List<VoiceSelectedListener> listeners = new ArrayList<VoiceSelectedListener>();

    public SwtHistoryBlock(Composite parent, Voice voice, SwtImageCache imageCache) {
        c = new Composite(parent, SWT.NONE);
        c.setLayout(new GridLayout(2, false));
        c.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));

        if (voice.getUser().equals(voice.getParent().getUser())) {
            // 左
            createImage(c, voice, imageCache);
            createBody(c, voice, imageCache);
        } else {
            // 右
            createBody(c, voice, imageCache);
            createImage(c, voice, imageCache);
        }

        Point p = c.computeSize(parent.getSize().x, SWT.DEFAULT);
//        c.setSize(p);
        log.info(p);
    }

    private Label createImage(Composite c, Voice voice, SwtImageCache cache) {
        Label l = new Label(c, SWT.BORDER);
        l.setImage(cache.getImage(voice.getUser().getThumbnail().getUrl(), 48, 48));
        GridData gd = new GridData(GridData.CENTER | GridData.HORIZONTAL_ALIGN_CENTER);
        gd.minimumWidth = 50;
        gd.minimumHeight = 50;

        l.setLayoutData(gd);

        return l;
    }

    private Label createBody(Composite c, Voice voice, SwtImageCache cache) {
        Label l = new Label(c, SWT.BORDER | SWT.WRAP);
        l.setText(voice.getBody(new SimpleStringVisitor()));

        l.setLayoutData(new GridData(GridData.FILL_BOTH));

        return l;
    }

    @Override
    public void addVoiceSelectedListener(VoiceSelectedListener listener) {
        listeners.add(listener);
    }

    @Override
    public void close() {
        c.dispose();
    }
}
